<?php
// 应用公共文件
use app\common\repositories\system\SystemConfigValueRepository;
use app\common\repositories\system\SystemGroupDataRepository;
use app\common\repositories\user\UserMemberRepository;
use basic\services\LocationService;
use think\db\BaseQuery;

if(!function_exists('success')){
    function success($data = ''){
        return app('json')->success($data);
    }
}

if(!function_exists('fail')){
    function fail($msg){
        return app('json')->fail($msg);
    }
}


if (!function_exists('systemConfig')) {

    function systemConfig($key)
    {
        return sysConfig('admin',$key);
    }
}

if (!function_exists('systemGroupData')) {
    function systemGroupData(string $key, ?int $page = null, ?int $limit = 10)
    {
        $make = app()->make(SystemGroupDataRepository::class);
        return $make->groupData($key, 'admin', $page, $limit);
    }
}

if (!function_exists('sysConfig')) {

    function sysConfig($type, $key)
    {
        $make = app()->make(SystemConfigValueRepository::class);
        if (is_array($key)) {
            $data = $make->more($key, $type);
        } else {
            $data = $make->get($key, $type);
        }
        return $data;
    }
}


function getAgreementArr(){
    return [
        'service_privacy'=>'服务协议与隐私条款',
        'consult_info'=>'咨询信息',
        'vip_member'=>'会员服务协议',
        'correlation'=>'相关协议',
        'about_us'=>'关于我们',
        'lawyer_service'=>'律师服务协议'
    ];
}



if(!function_exists('isDebug')){
    function isDebug(){
        return env('APP_DEBUG') == true;
    }
}


if(!function_exists('address2location')){
    function address2location($address){
        return LocationService::create()->address2Location($address);
    }
}


if (!function_exists('formatCascaderData')) {
    function formatCascaderData(&$options, $name, $baseLevel = 0, $pidName = 'pid', $pid = 0, $level = 0, $data = []): array
    {
        $_options = $options;
        foreach ($_options as $k => $option) {
            if ($option[$pidName] == $pid) {
                $value = ['value' => $k, 'label' => $option[$name]];
                unset($options[$k]);
                $value['children'] = formatCascaderData($options, $name, $baseLevel, $pidName, $k, $level + 1);
                if (!count($value['children'])) unset($value['children']);
                $data[] = $value;
            }
        }
        return $data;
    }
}

if(!function_exists('getOrderSn')) {
    function getOrderSn($prefix)
    {
        // 时间戳 42字节
        $time = floor(microtime(true) * 1000);
        // 当前时间 与 开始时间 差值
        $time -= 1479533469598;
        // 二进制的 毫秒级时间戳
        $base = decbin(12345 + $time);
        // 机器id  10 字节
        $machineid = str_pad(decbin('1'), 10, "0", STR_PAD_LEFT);
        // 序列数 12字节
        $random = str_pad(decbin(mt_rand(0, 4095)), 12, "0", STR_PAD_LEFT);
        // 拼接
        $base = $base.$machineid.$random;
        // 转化为 十进制 返回
        return $prefix.bindec($base);
    }

}



if (!function_exists('formToData')) {
    function formToData($form): array
    {
        $rule = $form->formRule();
        $action = $form->getAction();
        $method = $form->getMethod();
        $title = $form->getTitle();
        $config = (object)$form->formConfig();
        return compact('rule', 'action', 'method', 'title', 'config');
    }
}


if (!function_exists('getModelTime')) {
    /**
     * @param BaseQuery $model
     * @param string $section
     * @param string $prefix
     * @param string $field
     * @return mixed
     * @day 2020-04-29
     */
    function getModelTime(BaseQuery $model, string $section, $prefix = 'create_time', $field = '-')
    {
        if (!isset($section)) return $model;
        switch ($section) {
            case 'today':
                $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('today')), date('Y-m-d H:i:s', strtotime('tomorrow -1second'))]);
                break;
            case 'week':
                $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('this week 00:00:00')), date('Y-m-d H:i:s', strtotime('next week 00:00:00 -1second'))]);
                break;
            case 'month':
                $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('first Day of this month 00:00:00')), date('Y-m-d H:i:s', strtotime('first Day of next month 00:00:00 -1second'))]);
                break;
            case 'year':
                $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('this year 1/1')), date('Y-m-d H:i:s', strtotime('next year 1/1 -1second'))]);
                break;
            case 'yesterday':
                $model->whereBetween($prefix, [date('Y-m-d H:i:s', strtotime('yesterday')), date('Y-m-d H:i:s', strtotime('today -1second'))]);
                break;
            case 'quarter':
                list($startTime, $endTime) = getMonth();
                $model = $model->where($prefix, '>', $startTime);
                $model = $model->where($prefix, '<', $endTime);
                break;
            case 'lately7':
                $model = $model->where($prefix, 'between', [date('Y-m-d', strtotime("-7 day")), date('Y-m-d H:i:s')]);
                break;
            case 'lately30':
                $model = $model->where($prefix, 'between', [date('Y-m-d', strtotime("-30 day")), date('Y-m-d H:i:s')]);
                break;
            default:
                if (strstr($section, $field) !== false) {
                    list($startTime, $endTime) = explode($field, $section);
                    if (strlen($startTime) == 4) {
                        $model->whereBetweenTime($prefix, date('Y-m-d H:i:s', strtotime($section)), date('Y-m-d H:i:s', strtotime($section . ' +1day -1second')));
                    } else {
                        if ($startTime == $endTime) {
                            $model = $model->whereBetweenTime($prefix, date('Y-m-d 0:0:0', strtotime($startTime)), date('Y-m-d 23:59:59', strtotime($endTime)));
                        } else {
                            $model = $model->whereBetweenTime($prefix, date('Y-m-d H:i:s', strtotime($startTime)), date('Y-m-d H:i:s', strtotime($endTime . ' +1day -1second')));
                        }
                    }
                }
                break;
        }
        return $model;
    }
}


if(!function_exists('getTimeArray')){
    function getTimeArray($date,$timezone = false): array
    {
        $map = [
            'day'=>[
                'start'=>'today',
                'arr_start'=>0,
                'arr_count'=>date('G')+1,
                'interval' =>' 1 hour',
                'format'=>'H:i',
            ],
            'week'=>[
                'start'=>'this week',
                'arr_count'=>7,
                'interval' =>' 1 day',
                'format'=>'l',
            ],
            'month'=>[
                'start'=>'first Day of this month',
                'arr_count'=>date('j'),
                'interval' =>' 1 day',
                'format'=>'j日',
            ],
            'year'=>[
                'start'=>'this year 1/1',
                'arr_count'=>date('n'),
                'interval' =>' 1 month',
                'format'=>'n月',
            ],
        ];

        if(!in_array($date,array_keys($map))) return [];
        $now = $map[$date];
        $start = date('Y-m-d 00:00:00',strtotime($now['start']));
        $timeArray = [];
        for ($i=0;$i<$now['arr_count'];$i++){
            $end = date('Y-m-d H:i:s',strtotime("{$start} + {$now['interval']} - 1 seconds"));
            $timeArray[date($now['format'],strtotime($start))] = !$timezone ? [$start,$end] : [strtotime($start),strtotime($end)];
            $start = date('Y-m-d H:i:s',strtotime("$end + 1 seconds"));
        }
        return $timeArray;
    }
}



if (!function_exists('formatTree')) {
    function formatTree(&$options, $name, $pidName = 'pid', $pid = 0, $level = 0, $data = []): array
    {
        $_options = $options;
        foreach ($_options as $k => $option) {
            if ($option[$pidName] == $pid) {
                $value = ['id' => $k, 'title' => $option[$name]];
                unset($options[$k]);
                $value['children'] = formatTree($options, $name, $pidName, $k, $level + 1);
                $data[] = $value;
            }
        }
        return $data;
    }
}

if (!function_exists('path_to_url')) {
    /**
     * 路径转url路径
     * @param $path
     * @return string
     */
    function path_to_url($path)
    {
        return trim(str_replace(DIRECTORY_SEPARATOR, '/', $path), '.');
    }
}


if (!function_exists('formatCategory')) {
    function formatCategory(array $data, string $idName = "id", string $fieldName = 'pid', $childrenKey = 'children',$pid = 0)
    {
        $items = [];
        foreach ($data as $item) {
            $items[$item[$idName]] = $item;


            //id=>$item
        }
        $result = array();
        foreach ($items as $item) {
            if (isset($items[$item[$fieldName]])) {
                $items[$item[$fieldName]][$childrenKey][] = &$items[$item[$idName]];
            } else if($item[$fieldName] == $pid){
                $result[] = &$items[$item[$idName]];
            }
        }
        return $result;
    }
}


if (!function_exists('filter_emoji')) {

    // 过滤掉emoji表情
    function filter_emoji($str)
    {
        $str = preg_replace_callback(    //执行一个正则表达式搜索并且使用一个回调进行替换
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);
        return $str;
    }
}


if (!function_exists('sendMessage')) {

    /**
     * 发送消息
     * @param array $data 数据
     * @param string $type 类型
     */
    function sendMessage(array $data,$type='sms')
    {
      if($type == 'sms'){
          try {
              $service = \basic\services\SmsService::create();
              $service->sendMessage($data);
          }catch (Exception $e){
            // throw new \think\exception\ValidateException($e->getMessage());
          }
      }
    }
}

if(!function_exists('getOrderSn')){
    function getOrderSn($prefix): string
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        return $prefix . $msectime . mt_rand(10000, max(intval($msec * 10000) + 10000, 98369));
    }
}



function camelize($uncamelized_words,$separator='_')
{
    $uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
    return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
}


function uncamelize($camelCaps,$separator='_')
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}

if(!function_exists('checkMemberAuth')){

    /**
     * @param $uid
     * @param $type string 权限类型
     * @param int|null $targetId 目标id
     * @param string $viewType 查看类型
     * @return bool
     * User: xiest
     * Date: 2021/10/29
     */
    function checkMemberAuth($uid, string $type, int $targetId = null, string $viewType = '')
    {
        /**@var $userMemberMake UserMemberRepository**/
        $userMemberMake = app()->make(UserMemberRepository::class);
        return $userMemberMake->authCheck($uid,$type,$targetId,$viewType);
    }
}

if (!function_exists('getDistance')) {

    function getDistance($lat1, $lng1, $lat2, $lng2)
    {
        //将角度转为狐度
        $radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371;
        return round($s, 1);
    }
}


if (!function_exists('image_to_base64')) {
    /**
     * 获取图片转为base64
     * @param string $avatar
     * @return bool|string
     */
    function image_to_base64($avatar = '', $timeout = 9)
    {
        try {
            $url = parse_url($avatar);
            $url = $url['host'];
            $header = [
                'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0',
                'Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
                'Accept-Encoding: gzip, deflate, br',
                'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
                'Host:' . $url
            ];
            $dir = pathinfo($url);
            $host = $dir['dirname'];
            $refer = $host . '/';
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_REFERER, $refer);
            curl_setopt($curl, CURLOPT_URL, $avatar);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
            curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            $data = curl_exec($curl);
            $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            curl_close($curl);
            if ($code == 200) {
                return "data:image/jpeg;base64," . base64_encode($data);
            } else {
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }
}

if (!function_exists('put_image')) {
    /**
     * 获取图片转为base64
     * @param string $avatar
     * @return bool|string
     */
    function put_image($url, $filename = '')
    {

        if ($url == '') {
            return false;
        }
        try {
            if ($filename == '') {

                $ext = pathinfo($url);
                if ($ext['extension'] != "jpg" && $ext['extension'] != "png" && $ext['extension'] != "jpeg") {
                    return false;
                }
                $filename = time() . "." . $ext['extension'];
            }

            //文件保存路径
            ob_start();
            readfile($url);
            $img = ob_get_contents();
            ob_end_clean();
            $path = 'public/uploads/qrcode';
            $fp2 = fopen($path . '/' . $filename, 'a');
            fwrite($fp2, $img);
            fclose($fp2);
            return $path . '/' . $filename;
        } catch (Exception $e) {
            return false;
        }
    }
}
